<template>
  <div>
    <!--添加国家按钮-->
    <el-button
        class="addCountry"
        type="primary"
        round
        @click="addCountry"
        style="background-color: #803f7d; border-color: #111111;">
      <i class="el-icon-plus" style="margin-right: 3px;"></i>添加国家
    </el-button>

    <!-- 搜索框 -->
    <el-input
        v-model="searchKeyword"
        placeholder="输入国家名称搜索"
        clearable
        style="width: 300px; float: right; margin-bottom: 20px;"
        @clear="fetchCountries"
        @keyup.enter.native="fetchCountries"
    >
      <el-button
          slot="append"
          icon="el-icon-search"
          @click="fetchCountries"
      />
    </el-input>

    <el-table
        :data="tableData"
        style="width: 100%"
        border
        v-loading="loading"
        :cell-style="{ borderRight: 'none' }"
        :header-cell-style="{ borderRight: 'none' }"
    >
      <el-table-column prop="countryName" label="国家"/>
      <el-table-column prop="id" label="ID"/>
      <el-table-column prop="countryEnglishName" label="英文"/>
      <el-table-column prop="continent" label="所属大陆">
        <template #default="{ row }">
          <el-tag effect="plain">{{ row.continent }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="productNumber" label="产品数量"/>
      <el-table-column prop="createTime" label="添加时间">
        <template #default="{ row }">
          <div style="white-space: pre-line">{{ formatTime(row.createTime) }}</div>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template #default="{ row }">
          <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
              active-color="#803f7d"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="180">
        <template #default="{ row }">
          <el-button
              size="mini"
              type="primary"
              plain
              @click="handleEdit(row)"
          >编辑</el-button>
          <el-button
              size="mini"
              type="danger"
              plain
              @click="handleDelete(row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        class="pagination"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />

    <!-- 添加弹窗 -->
    <el-dialog
        :title="isEditMode ? '编辑国家' : '添加国家'"
        :visible.sync="dialogVisible"
        width="500px"
        :close-on-click-modal="false"
    >
      <el-form
          ref="formRef"
          :model="formData"
          label-width="90px"
          :rules="formRules"
      >
        <el-form-item label="国家名称" prop="countryName">
          <el-input
              v-model="formData.countryName"
              placeholder="请输入国家中文名称"
          />
        </el-form-item>
        <el-form-item label="英文名称" prop="countryEnglishName">
          <el-input
              v-model="formData.countryEnglishName"
              placeholder="请输入国家英文名称"
          />
        </el-form-item>
        <el-form-item label="所属大陆" prop="continent">
          <el-select
              v-model="formData.continent"
              placeholder="请选择所属大陆"
              style="width: 100%"
          >
            <el-option
                v-for="item in continentOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="国家图片" prop="imageUrl">
          <el-upload
          class="country-image-uploader"
          :action="`${baseUrl}/admin/admin/country/upload`"
          :show-file-list="false"
          :on-success="handleImageSuccess"
          :before-upload="beforeImageUpload"
          :headers="uploadHeaders"
      >
          <img v-if="formData.imageUrl" :src="formData.imageUrl" class="country-image">
          <i v-else class="el-icon-plus country-image-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="显示状态">
          <el-switch
              v-model="formData.status"
              :active-value="1"
              :inactive-value="0"
              active-text="显示"
              inactive-text="隐藏"
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button
            type="primary"
            :loading="submitting"
            @click="submitForm"
        >确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import axios from '@/utils/request'
import dayjs from 'dayjs';
export default {
  data() {
    return {
      baseUrl: 'https://visa.goldenholiday.com', 
      // 表格数据
      tableData: [],
      loading: false,

      // 分页相关
      currentPage: 1,
      pageSize: 10,
      total: 0,

      // 搜索相关
      searchKeyword: '',

      // 弹窗相关
      dialogVisible: false,
      isEditMode: false,
      submitting: false,
      formData: {
        id: null,
        countryName: '',
        countryEnglishName: '',
        continent: '',
        status: 1,
        imageUrl: ''
      },

      // 表单验证规则
      formRules: {
        countryName: [
          { required: true, message: '请输入国家名称', trigger: 'blur' }
        ],
        countryEnglishName: [
          { required: true, message: '请输入英文名称', trigger: 'blur' }
        ],
        continent: [
          { required: true, message: '请选择所属大陆', trigger: 'change' }
        ]
      },


      // 大陆选项
      continentOptions: [
        { value: '亚洲', label: '亚洲' },
        { value: '欧洲', label: '欧洲' },
        { value: '北美洲', label: '北美洲' },
        { value: '南美洲', label: '南美洲' },
        { value: '非洲', label: '非洲' },
        { value: '大洋洲', label: '大洋洲' },
        { value: '南极洲', label: '南极洲' }
      ]
    }
  },
  computed: {
            uploadHeaders() {
                return {
                    'Cache-Control': 'no-cache',
                    'token': window.localStorage.getItem('token')
                }
            }
        },
  mounted() {
    this.fetchCountries()
  },
  methods: {
    // 获取国家列表
    async fetchCountries() {
      this.loading = true;
      try {
        const res = await axios.get('/admin/country/page', {
          params: {
            page: this.currentPage,
            pageSize: this.pageSize,
            name: this.searchKeyword,
            _: Date.now()
          }
        });
        console.log('fetchCountries response:', res); // 添加调试
        // 兼容不同响应结构
        const records = res.records || res.data?.records || [];
        const total = res.total || res.data?.total || 0;

        this.tableData = records;
        this.total = total;
      } catch (error) {
        this.$message.error('数据加载失败');
      } finally {
        this.loading = false;
      }
    },
    // 打开添加弹窗
    addCountry() {
      this.isEditMode = false
      this.formData = {
        id: null,
        countryName: '',
        countryEnglishName: '',
        continent: '',
        status: 1,
        imageUrl: ''
      }
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs.formRef?.clearValidate()
      })
    },

    // 打开编辑弹窗
    handleEdit(row) {
        console.log('编辑前的行数据：', row);
        this.isEditMode = true;
        this.dialogTitle = '编辑用户';
        this.dialogVisible = true;
        this.formData = {
            id: row.id,
            countryName: row.countryName,
            countryEnglishName: row.countryEnglishName,
            continent: row.continent,
            status: row.status,
            imageUrl: row.imageUrl || ''  // 确保 imageUrl 不为 null
        };
    },
    
    handleImageSuccess(res, file) {
      console.log('上传响应：', res);
      console.log('文件信息：', file);
      if (res.code === 1) {
          // 如果返回的是完整URL就直接使用，否则拼接baseUrl
          this.formData.imageUrl = res.data.startsWith('http') ? res.data : this.baseUrl + res.data;
          console.log('设置的图片URL：', this.formData.imageUrl);
          this.$message.success('图片上传成功');
      } else {
          this.$message.error(res.msg || '上传失败');
      }
    },
    
    // 图片上传前的验证
    beforeImageUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error('只能上传图片文件!');
        return false;
      }
      if (!isLt2M) {
        this.$message.error('图片大小不能超过 2MB!');
        return false;
      }
      return true;
    },

    // 提交表单
    async submitForm() {
        try {
            await this.$refs.formRef.validate();
            this.submitting = true;

            const payload = { ...this.formData };
            console.log('提交的数据：', payload);

            let res;
            if (this.isEditMode) {
                console.log('执行编辑操作');
                res = await axios.put('/country', payload);
            } else {
                console.log('执行新增操作');
                // 修改为正确的新增接口
                res = await axios.post('/country/add', payload);
            }

            if (res.code === 1) {
                this.$message.success(this.isEditMode ? '修改成功' : '添加成功');
                this.dialogVisible = false;
                this.fetchCountries();
            } else {
                throw new Error(res.msg || '操作失败');
            }
        } catch (error) {
            console.error('提交表单错误：', error);
            this.$message.error(error.message || '提交失败');
        } finally {
            this.submitting = false;
        }
    },
    // 删除国家
    async handleDelete(row) {
      try {
        await this.$confirm(`确定删除【${row.countryName}】吗？`, '提示', { type: 'warning' });
        const that = this
        // 确保传递正确参数
        axios.delete('/country', {
          params: { id: row.id }
        }).then(function(res){
          if (res.code === 1) {
            console.log('success this.$message:', that.$message)
            that.$message.success('删除成功');
            that.fetchCountries();
          } else {
            console.log('error this.$message:', that.$message)
            throw new Error(res.msg || '删除失败');
          }
        }).catch(function (error) {
          if (error.response?.status === 404) {
            that.$message.error('记录不存在或已被删除');
          } else if (error !== 'cancel') {
            that.$message.error(error.message || '删除失败');
          }
        })

      } catch (error) {
        if (error.response?.status === 404) {
          this.$message.error('记录不存在或已被删除');
        } else if (error !== 'cancel') {
          this.$message.error(error.message || '删除失败');
        }
      }
    },
    async handleStatusChange(row) {
      const originalStatus = row.status;
      try {
        const res = await axios.post(`/country/status/${row.status}`, null, {
          params: { id: row.id }
        });

        if (res.code === 1) {
          this.$message.success('状态更新成功');
          // 在状态更新成功后，手动更新 tableData
          const index = this.tableData.findIndex(item => item.id === row.id);
          if (index !== -1) {
            // 使用 $set 确保 Vue 能够检测到数组的变化
            this.$set(this.tableData, index, { ...this.tableData[index], status: row.status });
          }
        } else {
          throw new Error(res.msg || '更新失败');
        }
      } catch (error) {
        this.$message.error(error.message || '更新失败');
        row.status = originalStatus;
      }
    },

    // 分页处理
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.fetchCountries();
    },

    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchCountries()
    },

    // 时间格式化
    formatTime(timeStr) {
      return timeStr ? dayjs(timeStr).format('YYYY-MM-DD HH:mm') : '-';
    },
  }
}
</script>

<style scoped>
.addCountry {
  margin-bottom: 20px;
  float: left;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

/* 调整表格行高 */
.el-table ::v-deep .el-table__row td {
  padding: 8px 0;
}

/* 弹窗表单样式 */
.el-form-item {
  margin-bottom: 18px;
}
.country-image-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.country-image-uploader:hover {
  border-color: #409EFF;
}
.country-image-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.country-image {
  width: 120px;
  height: 120px;
  display: block;
}
</style>